var datatable;// 定义一个全局的dataTable
var d;
var paras;//参数
$(function() {
	$("#groupId").combobox();
	$("#terminalBrandId").combobox({
		select:function(event,ui){
			loadTerminalModel();
		}
	});
	$("#terminalModelId").combobox();
	$("#apnId").combobox();
	$("#osId").combobox();
	initSelectRadio();
	
	isGoing();

	$('#table tbody').on('click', 'tr', function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
		} else {
			datatable.$('tr.selected').removeClass('selected');
			$(this).addClass('selected');
		}
	});
})

function isGoing(){
	var callId = $("#callId").val();
	if(callId){
		var terminalBrandId = $("#terminalBrandId").val();
		if(terminalBrandId){
			loadTerminalModel();
		}
		getList();
	}
}

function initSelectRadio(){
	var selectedvalue = $("#selectedvalue").val();
	if(selectedvalue){
		$("#selectedvalue_"+selectedvalue).attr("checked",'checked'); 
		getRadio();
	}
}
/**
 * 获得单选框
 */
function getRadio() {
	
	var selectedvalue = $("input[name='radio']:checked").val();
	for (var i = 0; i < 6; i++) {
		var tempId = '#radio_' + i;
		if (selectedvalue == i) {
			$(tempId).show();
		} else {
			$(tempId).hide();
		}
	}
}
/**
 * 根据终端类型，加载终端型号
 * 
 * @param parentid
 */
function loadTerminalModel() {
	var terminalBrand = $("#terminalBrandId").val();
	$.ajax({
		url : '../../feature/terminalUE/terminalModelInfos?terminalBrand='
				+ terminalBrand,
		type : 'POST',
		dataType : 'JSON',
		error : function() {
			alert('Error loading data!');
		},
		success : function(msg) {
			$("#terminalModelId").remove();
			$("#terminalModelTD").append($("<select id='terminalModelId' name='terminalModelId'></select>"));
			$("#terminalModelId").combobox();
			var list = msg.terminalModelList;
			var terminalModelSelected =  $("#terminalModelSelected").val();
			if(terminalModelSelected){
				$.each(eval(list), function(i, item) {
					if(terminalModelSelected==item.terminal_model){
						$(
								"<option selected='selected' value='" + item.terminal_model + "'>"
								+ item.terminal_model + "</option>")
								.appendTo($("#terminalModelId"));
					}else{
						$(
								"<option value='" + item.terminal_model + "'>"
								+ item.terminal_model + "</option>")
								.appendTo($("#terminalModelId"));
					}
				});

			}else{
				
				$.each(eval(list), function(i, item) {
					$(
							"<option value='" + item.terminal_model + "'>"
							+ item.terminal_model + "</option>")
							.appendTo($("#terminalModelId"));
				});
			}
		}
	});
}

/**
 * 查询form重置
 */
function resetQueryForm() {
	$('#queryForm')[0].reset();
	getRadio();
	
}


var condition;

/**
 * 拼接查询条件
 * 
 * @returns
 */
function getCondition(selectRadio,groupIdByUserGroup) {
	//查询一次，清空一次，保证转存的是上次查询的数据
	delete condition;
	condition = {};
	
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();
	condition['beginDate'] = beginDate;
	condition['endDate'] = endDate;
	
	//var selectRadio = $('input:radio[name="radio"]:checked').val();
	condition['selectRadio'] = selectRadio;
	if (selectRadio == 0) {
		if(groupIdByUserGroup){
			condition['groupId'] = groupIdByUserGroup;
		}else{
			condition['groupId'] = $("#groupId").val();
		}
	} else if (selectRadio == 1) {
		var userId = $("#userId").val();
		condition['userId'] = userId;
	} else if (selectRadio == 2) {
		var terminalBrandId = $("#terminalBrandId").val();
		var terminalModelId = $("#terminalModelId").val();
		condition['terminalBrandId'] = terminalBrandId;
		condition['terminalModelId'] = terminalModelId;
	} else if (selectRadio == 3) {
		var apnId = $("#apnId").val();
		condition['apnId'] = apnId;
	} else if (selectRadio == 4) {
		var osId = $("#osId").val();
		condition['osId'] = osId;
	} else if (selectRadio == 5) {
		var flowTypeId = $("#flowTypeId").val();
		var operationId = $("#operationId").val();
		var flowValueId = $("#flowValueId").val();
		condition['flowTypeId'] = flowTypeId;
		condition['operationId'] = operationId;
		condition['flowValueId'] = flowValueId;
	}

	return condition;
}

function valiCondition() {
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();
	var selectRadio = $('input:radio[name="radio"]:checked').val();
	var terminalModelId = $("#terminalModelId").val();
	var apnId = $("#apnId").val();
	if (beginDate == "") {
		alert("请选择开始时间！");
		return false;
	}
	
	if (endDate == "") {
		alert("请选择结束日期！");
		return false;
	}

	if (selectRadio == "2" && (terminalModelId == null || terminalModelId == "")) {
		alert("请选择终端型号！");
		return false;
	}
	
	if (selectRadio == "3" && (apnId == null || apnId == "")) {
		alert("请选择APN！");
		return false;
	}
	
	if(!validatiorHourDiff(beginDate,endDate)){
		alert("开始时间和结束时间间隔大于24小时，请重新选择时间！");
		return false;
	}
	return true;
}

/**
 * 开始时间和结束时间之间的间隔小于24小时时，返回true，否则返回false，
 * 时间参数格式：yyyy-MM-dd HH
 */
function validatiorHourDiff(beginDate, endDate) {
	beginDate += ":00:00";
	endDate += ":00:00";
	// 将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式
	var begin = beginDate.replace(/\-/g, "/");
	var end = endDate.replace(/\-/g, "/");

	var beginTime = new Date(begin).getTime(); // 开始时间
	var endTime = new Date(end).getTime(); // 结束时间

	var hourDiff = (endTime - beginTime) / (1000 * 3600);
	if (hourDiff > 24) {
		return false;
	}
	return true;
}
/**
 * 获得list信息
 */
function getList() {
	$("#theadtrId").show();
	if (valiCondition()) {
		var selectRadio = $('input:radio[name="radio"]:checked').val();
		var beginDate = $("#beginDate").val();
		var endDate = $("#endDate").val();
		var groupId = $("#groupId").val();
		var byUserGroup = $("#byUserGroup").val();
		
		var userId = $("#userId").val();
		var terminalBrandId = $("#terminalBrandId").val();
		var terminalModelId = $("#terminalModelId").val();
		var apnId = $("#apnId").val();
		var osId = $("#osId").val();
		var flowTypeId = $("#flowTypeId").val();
		var operationId = $("#operationId").val();
		var flowValueId = $("#flowValueId").val();
		if(byUserGroup){
			groupId = byUserGroup;
			selectRadio = 0;
		}
		//getCondition(selectRadio,byUserGroup);
		//$("#table tbody tr").remove();
		$("#tbodyId").remove();
		$('#table').append($("<tbody id='tbodyId'></tbody>"));
		if (datatable == undefined || datatable == "undefined"
				|| datatable == null) {
		} else {
			datatable.fnDestroy();
		}
		datatable = $('#table').dataTable({
			"aoColumnDefs" : [ {
				sDefaultContent : '',
				aTargets : [ '_all' ]
			} ],
			"bPaginate" : true, // 翻页功能
			"bLengthChange" : false, // 改变每页显示数据数量
			"bFilter" : false, // 过滤功能
			"bSort" : true, // 排序功能
			"bInfo" : true,// 页脚信息
			"bAutoWidth" : true,// 自动宽度
			// "sPaginationType": "full_numbers",//显示分页的样式 还有simple_numbers等
//			"scrollX" : true,
//			"sScrollXInner" : "100%",
			"iDisplayLength" : 50,
			"sScrollXInner" : "110%",
			"bScrollCollapse" : true,
			"oLanguage" : {
				"sLengthMenu" : "每页显示 _MENU_条",
				"sZeroRecords" : "没有找到符合条件的数据",
				"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
				"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
				"sInfoEmpty" : "没有记录",
				"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
				"sSearch" : "搜索：",
				"oPaginate" : {
					"sFirst" : "首页",
					"sPrevious" : "前一页",
					"sNext" : "后一页",
					"sLast" : "尾页"
				}
			},
			"bProcessing" : true,
			"bServerSide" : true,
			"sAjaxSource" : "../../businessAnalysis/userPerformance/infos",
			"fnServerData" : function(sSource, aoData, fnCallback) {
				delete paras;
				paras = {
						"aoData" : JSON.stringify(aoData),
						"selectRadio" : selectRadio,
						"beginDate":beginDate,
						"endDate" : endDate,
						"groupId" :groupId,
						"userId" :userId,
						"terminalBrandId":terminalBrandId,
						"terminalModelId":terminalModelId,
						"apnId":apnId,
						"osId" :osId,
						"flowTypeId" :flowTypeId,
						"operationId":operationId,
						"flowValueId":flowValueId
					};
				
				$.ajax({
					"type" : "post",
					"contentType" : "application/x-www-form-urlencoded",
					"url" : sSource,
					"dataType" : "json",
					"data" : paras, // 以json格式传递
					"success" : function(resp) {
						fnCallback(resp.pageDate);
						d = resp.allData;
					}
				});
			},
			columns : [ {
				data : "msisdn",
				render : function(value, type, row) {
					if (value == null || value == "") {
						value = "";
					}
					return value;
				}
			}, {
				data : "imsi",
				render: function (data, type, row) {
					if(data==undefined){
						return "";
					}else{
						var msisdn = row.msisdn;
						return "<a href='#' onclick=\"forwordInterfaceUser('"+msisdn+"')\"  >"+data+"</a>";
					}
	            }
			}, {
				data : "area_code"
			}, {
				data : "city_code"
			}, {
				data : "terminal_brand"
			}, {
				data : "apn_name"
			}, {
				data : "terminal_os"
			}, {
				data : "flow_total"
			}, {
				data : "flow_up"
			}, {
				data : "flow_down"
			}, {
				data : "attach_ratio"
			}, {
				data : "session_ratio"
			}, {
				data : "tau_ratio"
			}, {
				data : "tcp_ratio"
			}, {
				data : "dns_ratio"
			}, {
				data : "interactive_ratio"
			}, {
				data : "download_speed"
			}, {
				data : "firstpacket_delay"
			} ]

		});
	}
}
/**
 * 导出数据
 */
function exportExcel(){
	if(d){
		$.ajax({
			type : "POST",
			url : "../../businessAnalysis/userPerformance/exportBigDataExcel?rand="
				+ Math.random(),
				dataType : "json",
				"data" : paras,
				success : function(data) {
					if (data.flag) {
						var url = "../../businessAnalysis/attachment/downFiles?path="
								+ data.path;
						window.location.href = url;
					} else {
						alert(data.msgs);
					}
				}
		});
	}else{
		alert("请先查询数据！");
	}
}


function addBox() {
	if(d){
		closeBox();
		var cont = '';
		cont += "<div id='modal-wizard' class='modal'>";
		cont += "            <div class='modal-dialog'>";
		cont += "                <div class='modal-content'>";
		cont += "                    <div class='modal-header' data-target='#modal-step-contents'>";
		cont += "                        <h3>用户组新增</h3>";
		cont += "                    </div>";
		cont += "                    <div class='modal-body step-content' id='modal-step-contents'>";
		cont += "                        <div class='' id='modal-step1'>";
		cont += "                            <div class='center'>";
		cont += "                                <form class='form-horizontal'>";
		
		cont += "                                    <div class='form-group'>";
		cont += "                                        <label for='groupName' class='col-sm-3 control-label no-padding-right' style='padding-top: 2px;'>用户组名称:</label>";
		cont += "                                        <div class='col-sm-9'>";
		cont += "                                            <input type='text'  id='groupName' name='1' class='col-sm-8' required>";
		cont += "                                        </div>";
		cont += "                                    </div>";
		
		cont += "                                    <div class='form-group'>";
		cont += "                                        <label for='groupRemark' class='col-sm-3 control-label no-padding-right' style='padding-top: 2px;'>用户组描述:</label>";
		cont += "                                        <div class='col-sm-9'>";
		cont += "                                            <input type='text'  id='groupRemark' name='1' class='col-sm-8'>";
		cont += "                                        </div>";
		cont += "                                    </div>";
		
		cont += "                                    <div class='form-group'>";
		cont += "                                        <label for='topn' class='col-sm-3 control-label no-padding-right' style='padding-top: 2px;'>条数:</label>";
		cont += "                                        <div class='col-sm-9'>";
		cont += "												<div style='float:left'><input type='radio' checked='checked' name='topn' onclick='topnType()' value='0'>全部</input></div>";
		cont += "												<div style='float:left;margin-left:20px'><input type='radio'  name='topn' onclick='topnType()' value='1'> Top N</input></div><div style='float:left;display: none' id='topnNumberDiv'><input id='topnNumberId' style='width:170px' type='text'/></div>";
		cont += "                                        </div>";
		cont += "                                    </div>";
		
		cont += "                                </form>";
		cont += "                            </div>";
		cont += "                        </div>";
		cont += "                    </div>";
		cont += "                    <div class='modal-footer wizard-actions'>";
		cont += "                        <button class='btn btn-success btn-sm btn-next save' data-last='完成' onclick='add()'>";
		cont += "                            完成";
		cont += "                            <i class='icon-ok'></i>";
		cont += "                        </button>";
		cont += "                        <button class='btn btn-danger btn-sm pull-left' data-dismiss='modal'>";
		cont += "                            <i class='icon-remove'></i>";
		cont += "                            取消";
		cont += "                        </button>";
		cont += "                    </div>";
		cont += "                </div>";
		cont += "            </div>";
		cont += "        </div>";
		$("body").append(cont);
		$('#modal-wizard').modal("show");
	}else{
		alert("请先选择数据！");
	}
}
//关闭盒子
function closeBox() {
    $('#modal-wizard').modal("hide");
    $('#modal-wizard').remove();
}

function topnType(){
	var topn = $("input[name='topn']:checked").val();
	if(topn=='0'){
		$("#topnNumberDiv").hide();
	}else if(topn=='1'){
		$("#topnNumberDiv").show();
	}
}

function validatorAddGroup(){
	var groupName = $("#groupName").val();
	if(groupName==""){
		alert("请输入组名称");
		return false;
	}
	
	var topn = $("input[name='topn']:checked").val();
	var topnNumber = $("#topnNumberId").val();
	if(topn == "1" && topnNumber=="" ){
		alert("请输入要转存的条数!");
		return false;
	}
	return true;
}
/**
 * 用户组信息添加
 */
function add() {
	if(validatorAddGroup()){
		var groupName = $("#groupName").val();
		var groupRemark = $("#groupRemark").val();
		var topn = $("input[name='topn']:checked").val();
		
		paras['groupName'] = groupName;
		paras['groupRemark'] = groupRemark;
		paras['topn'] = topn;
		
		if(topn=="0"){
			
		}else if(topn == "1"){
			var topnNumber = $("#topnNumberId").val();
			paras['topnNumber'] = topnNumber;
		}
		
		$.ajax({
			type: "POST",
			async: false,
			url: "../../businessAnalysis/userPerformance/addGroupByCondition",
			//data: {content: JSON.stringify(content)},
			data:paras,
			dataType: "json",
			success: function(data) {
					alert(data.msgs);
					closeBox();
			}
		});
	}
   // windowReload();
}

function forwordInterfaceUser(msisdn){
	var beginDate = condition.beginDate;
	var endDate = condition.endDate;
	var url="/excavantionAnalysis/useranalysis/report?msisdn="+msisdn +"&beginDate="+beginDate +"&endDate="+endDate+"&userType=msisdn";
	//window.location.href=url;
	linkTab("用户分析",url);
}